<template>
  <a-modal
    :visible="visible"
    title="任务反馈"
    :width="1200"
    :footer="false"
    @cancel="onCancel"
    @update:visible="onUpdateVisible"
  >
    <a-form ref="formRef" :model="localForm" layout="vertical">
      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item label="督办来源">
            <a-input v-model="localForm.source" disabled />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="问题类型">
            <a-input v-model="localForm.problemType" disabled />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item label="督察要求">
            <a-input v-model="localForm.requirements" disabled />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="领导批示">
            <a-checkbox v-model="localForm.leaderInstruction" style="margin-right: 24px; white-space: nowrap" disabled>
              批示
            </a-checkbox>
            <template v-if="localForm.leaderInstruction">
              <a-input v-model="localForm.leaderRemark" disabled style="width: 180px; margin-left: 12px" />
              <label style="margin-right: 8px; min-width: 70px">相关文件</label>
              <a-upload :file-list="localForm.leaderFiles" disabled />
            </template>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row :gutter="16">
        <a-col :span="24">
          <a-form-item label="整改问题清单">
            <a-table
              :columns="problemColumns"
              :data="localForm.problemList ?? []"
              :pagination="false"
              row-key="index"
              bordered
              table-layout="auto"
              style="width: 100%"
            >
              <template #problemDesc="{ record }">
                <a-textarea
                  v-model="record.problemDesc"
                  disabled
                  :auto-size="{ minRows: 2, maxRows: 6 }"
                  style="white-space: pre-wrap; word-break: break-all"
                />
              </template>
              <template #status="{ record }">
                <a-tag
                  :color="
                    record.status === 'pendingReview'
                      ? 'green'
                      : record.status === 'reject'
                        ? 'red'
                        : record.status === 'reviewed'
                          ? 'blue'
                          : 'orange'
                  "
                >
                  {{
                    record.status === 'notRectified' || record.status == null
                      ? '未整改'
                      : record.status === 'pendingReview'
                        ? '待复核'
                        : record.status === 'reviewed'
                          ? '已复核'
                          : record.status === 'reject'
                            ? '已驳回'
                            : record.status
                  }}
                </a-tag>
              </template>
              <template #action="{ record }">
                <template v-if="record.status !== 'reviewed'">
                  <a-space>
                    <a-button size="small" @click="openRectifyModal(record)">
                      {{
                        record.status === 'pendingReview'
                          ? '编辑整改'
                          : record.status === 'reject'
                            ? '重新整改'
                            : record.status === 'reviewed'
                              ? '查看整改'
                              : '整改'
                      }}
                    </a-button>
                    <a-button
                      v-if="record.status === 'reject'"
                      size="small"
                      type="outline"
                      @click="showRejectReason(record)"
                    >
                      驳回原因
                    </a-button>
                  </a-space>
                </template>
              </template>
            </a-table>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item label="整改单位">
            <a-input v-model="rfGroupNames" disabled />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="整改人员">
            <a-input v-model="rfUserNames" disabled />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item label="整改期限">
            <a-input v-model="rfDateDisplay" disabled />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="审核人">
            <a-input v-model="localForm.auditorName" disabled />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item label="备注">
            <a-input v-model="localForm.remark" disabled />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="相关附件">
            <a-upload :file-list="localForm.attachments" disabled />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item label="填报单位">
            <a-input v-model="localForm.reportDeptName" disabled />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="填报人">
            <a-input v-model="localForm.reportUser" disabled />
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
    <div style="text-align: right; margin-top: 24px">
      <a-button @click="onCancel" style="margin-right: 8px">取消</a-button>
      <a-button @click="onConfirm" type="primary">提交反馈</a-button>
    </div>
    <!-- 整改弹框 -->
    <a-modal v-model:visible="rectifyModalVisible" title="整改问题" :footer="false" width="600">
      <a-form :model="rectifyForm" layout="vertical">
        <a-form-item label="核实情况">
          <a-textarea
            v-model="rectifyForm.checkMessage"
            :auto-size="{ minRows: 2, maxRows: 4 }"
            placeholder="请输入核实情况"
          />
        </a-form-item>
        <a-form-item label="整改措施">
          <a-textarea
            v-model="rectifyForm.rfMeasures"
            :auto-size="{ minRows: 2, maxRows: 4 }"
            placeholder="请输入整改措施"
          />
        </a-form-item>
      </a-form>
      <div style="text-align: right; margin-top: 24px">
        <a-button @click="rectifyModalVisible = false" style="margin-right: 8px">取消</a-button>
        <a-button type="primary" @click="saveRectify">保存</a-button>
      </div>
    </a-modal>

    <!-- 驳回原因弹框 -->
    <a-modal v-model:visible="rejectReasonVisible" title="驳回原因" :footer="false" width="500">
      <div style="padding: 20px 0">
        <div style="display: flex; align-items: flex-start; margin-bottom: 16px">
          <div style="flex: 1">
            <div
              style="
                background: #fff2f0;
                border: 1px solid #ffccc7;
                border-radius: 6px;
                padding: 12px 16px;
                color: #333;
                line-height: 1.6;
                font-size: 14px;
                min-height: 60px;
                white-space: pre-wrap;
                word-break: break-all;
              "
            >
              {{ rejectReasonMessage || '暂无驳回原因' }}
            </div>
          </div>
        </div>
      </div>
      <div style="text-align: right; margin-top: 24px; border-top: 1px solid #f0f0f0; padding-top: 16px">
        <a-button @click="rejectReasonVisible = false" type="primary">我知道了</a-button>
      </div>
    </a-modal>
  </a-modal>
</template>

<script setup lang="ts">
  import { computed, ref, watch } from 'vue';
  import { Message } from '@arco-design/web-vue';
  import { processed, processProblem } from '@/api/task';
  import { getUserNameByIds } from '@/api/user';
  import { getGroupNameByIds } from '@/api/group';

  const props = defineProps({
    visible: Boolean,
    form: Object
  });
  const emits = defineEmits(['update:visible', 'refresh']);
  const localForm = ref<any>({});
  const formRef = ref();
  const rfUserNames = ref<string>('');
  const rfGroupNames = ref<string>('');
  const processContent = ref('');
  const rectifyModalVisible = ref(false);
  const rectifyForm = ref({ checkMessage: '', rfMeasures: '' });
  let currentRectifyRecord: any = null;

  // 驳回原因相关状态
  const rejectReasonVisible = ref(false);
  const rejectReasonMessage = ref('');

  const problemColumns = [
    { title: '序号', dataIndex: 'index', width: 60 },
    { title: '问题描述', dataIndex: 'problemDesc', slotName: 'problemDesc' },
    { title: '整改状态', dataIndex: 'status', slotName: 'status', width: 100 },
    { title: '操作', dataIndex: 'action', slotName: 'action', width: 100 }
  ];

  // 计算属性
  const rfDateDisplay = computed(() => {
    if (!localForm.value?.rfStartDate || !localForm.value?.rfEndDate) return '';
    const d1 = new Date(localForm.value.rfStartDate);
    const d2 = new Date(localForm.value.rfEndDate);
    return `${d1.getFullYear()}年${String(d1.getMonth() + 1).padStart(2, '0')}月${String(d1.getDate()).padStart(2, '0')}日 - ${d2.getFullYear()}年${String(d2.getMonth() + 1).padStart(2, '0')}月${String(d2.getDate()).padStart(2, '0')}日`;
  });

  // 监听props.form变化
  watch(
    () => props.form,
    val => {
      if (val && Object.keys(val).length) {
        localForm.value = { ...val };
      } else {
        localForm.value = {};
      }
    },
    { immediate: true, deep: true }
  );

  // 监听整改人员变化
  watch(
    () => localForm.value.rfUsers,
    async newVal => {
      if (newVal) {
        const ids = typeof newVal === 'string' ? newVal.split(',') : newVal;
        try {
          const res = await getUserNameByIds(ids);
          if (Array.isArray(res.data)) {
            const names = res.data.map(item => item.name || '').filter(name => name);
            rfUserNames.value = names.join('，');
          } else {
            rfUserNames.value = '';
          }
        } catch (e) {
          rfUserNames.value = '';
        }
      } else {
        rfUserNames.value = '';
      }
    },
    { immediate: true }
  );

  // 监听整改单位变化
  watch(
    () => localForm.value.rfUnits,
    async newVal => {
      if (newVal) {
        const ids = typeof newVal === 'string' ? newVal.split(',') : newVal;
        try {
          const res = await getGroupNameByIds(ids);
          if (Array.isArray(res.data)) {
            const names = res.data.map(item => item.groupName || '').filter(name => name);
            rfGroupNames.value = names.join('，');
          } else {
            rfGroupNames.value = '';
          }
        } catch (e) {
          rfGroupNames.value = '';
        }
      } else {
        rfGroupNames.value = '';
      }
    },
    { immediate: true }
  );

  // 监听弹框显示状态
  watch(
    () => props.visible,
    v => {
      if (!v) {
        processContent.value = '';
      }
    }
  );

  function onCancel() {
    emits('update:visible', false);
  }

  function onUpdateVisible(v: boolean) {
    emits('update:visible', v);
  }

  async function onConfirm() {
    // 校验整改问题清单
    const problemList = localForm.value.problemList || [];
    const hasUnrectified = problemList.some(
      item => item.status === 'notRectified' || item.status === null || item.status === undefined
    );
    const hasRejected = problemList.some(item => item.status === 'reject');
    if (hasUnrectified || hasRejected) {
      Message.warning('存在未整改或已驳回的问题，不能提交反馈');
      return;
    }
    try {
      await processed(localForm.value.taskId);
      Message.success('反馈成功');
      emits('update:visible', false);
      emits('refresh');
    } catch (e) {
      console.log(e);
      Message.error('反馈失败');
    }
  }

  function openRectifyModal(record) {
    currentRectifyRecord = record;
    rectifyForm.value.checkMessage = record.checkMessage || '';
    rectifyForm.value.rfMeasures = record.rfMeasures || '';
    rectifyModalVisible.value = true;
  }

  function saveRectify() {
    if (!rectifyForm.value.checkMessage || !rectifyForm.value.rfMeasures) {
      Message.error('请填写完整的核实情况和整改措施');
      return;
    }
    if (currentRectifyRecord) {
      console.log('currentRectifyRecord', localForm.value);
      // 调用后端接口
      processProblem({
        problemId: currentRectifyRecord.problemId,
        taskId: localForm.value.taskId,
        checkMessage: rectifyForm.value.checkMessage,
        rfMeasures: rectifyForm.value.rfMeasures
      })
        .then(() => {
          currentRectifyRecord.verifyInfo = rectifyForm.value.checkMessage;
          currentRectifyRecord.rectifyMeasure = rectifyForm.value.rfMeasures;
          currentRectifyRecord.status = 'pendingReview';
          Message.success('整改已提交');
          rectifyModalVisible.value = false;
        })
        .catch(() => {
          Message.error('整改提交失败');
        });
    }
  }

  function showRejectReason(record) {
    rejectReasonMessage.value = record.message || '暂无驳回原因';
    rejectReasonVisible.value = true;
  }

  // 初始化问题清单的整改字段
  watch(
    () => localForm.value.problemList,
    list => {
      if (Array.isArray(list)) {
        list.forEach(item => {
          if (!('status' in item)) item.status = 'notRectified';
          if (!('verifyInfo' in item)) item.verifyInfo = '';
          if (!('rectifyMeasure' in item)) item.rectifyMeasure = '';
        });
      }
    },
    { immediate: true, deep: true }
  );
</script>
